package com.tg.app.activity.device.settings;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import com.demo.view.IPEditText;
import com.tg.app.R;
import com.tg.app.TGDevice;
import com.tg.app.activity.base.DeviceSettingsBaseActivity;
import com.tg.app.activity.device.DeviceSettingsActivity;
import com.tg.data.bean.DeviceSettingsInfo;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.Camera;
import com.tange.module.camera.hub.CameraHub;
import com.tg.data.media.OnICameraListener;
import com.tg.appcommon.android.Packet;
import com.tg.data.http.entity.SMsgAVIoctrlIPCONFIGRespBean;
import com.demo.view.SettingItemView;
import com.tg.appcommon.android.DialogUtil;
import com.tg.appcommon.android.ResourcesUtil;
import com.tange.base.toolkit.StringUtils;
import com.tg.appcommon.android.TGLog;
import com.tange.base.toolkit.TGThreadPool;
import com.tg.appcommon.android.TGToast;

import java.util.ArrayList;
import java.util.List;

public class NetworkSettingsActivity extends DeviceSettingsBaseActivity implements OnICameraListener, IPEditText.IpEditTextWatcher {
    private DeviceSettingsInfo mDeviceSettingsInfo;
    private static final int AUTO_CONFIG_VAL = 1;
    public static final String NETWORK_CONFIG = "ip_network_config";
    private boolean mSaved = false;
    private Camera mCamera;
    private SMsgAVIoctrlIPCONFIGRespBean mSMsgAVIoctrlIPCONFIGResp;
    private int bDhcpEnabled = AUTO_CONFIG_VAL;
    private IPEditText ipAdress, ndsEdit, nds2Edit, markEdit, gatewayEdit;
    private SettingItemView autoSettingItem, manuSettingItem;

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    public void receiveUpdateConnectStates(int state) {
        TGLog.d(TGLog.TAG, "===mDeviceSettingsInfo.deviceStatus = " + state);
        if (state == Camera.CONNECTION_STATE_DISCONNECTED){
            TGThreadPool.executeOnUiThread(() -> {

            });
        }
    }


    @Override
    public void receiveIOCtrlData(int type, byte[] data) {
        if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SETRECORD_RESP) {
            byte result = data[3];
            TGLog.d(TGLog.TAG, "type" + type + ", result = " + result);
            completeSend();
            if (result == 0) {
                runOnUiThread(() -> sendUpdateSettingBroadcast(mDeviceSettingsInfo));
            }else{
                TGThreadPool.executeOnUiThread(() -> {
                });

            }
        } else if (type == AVIOCTRLDEFs.TCI_CMD_SET_COMMAND_RESP) {
            int command = Packet.byteArrayToInt_Little(data, 0);
            int result = Packet.byteArrayToInt_Little(data, 4);
            if (command == AVIOCTRLDEFs.TCI_CMD_SET_IPCONFIG_REQ){
                TGLog.d("TCI_CMD_SET_IPCONFIG_REQ");
                TGToast.showToast(result == 0? R.string.alert_sound_custom_save_completed : R.string.alert_sound_custom_save_failed);
                if (result == 0){
                    if (mSMsgAVIoctrlIPCONFIGResp != null){
                        mSMsgAVIoctrlIPCONFIGResp.bDhcpEnabled = bDhcpEnabled;
                        mSMsgAVIoctrlIPCONFIGResp.setIp(ipAdress.getIpText());
                        mSMsgAVIoctrlIPCONFIGResp.setDns1(ndsEdit.getIpText());
                        mSMsgAVIoctrlIPCONFIGResp.setDns2(nds2Edit.getIpText());
                        mSMsgAVIoctrlIPCONFIGResp.setGateway(gatewayEdit.getIpText());
                        mSMsgAVIoctrlIPCONFIGResp.setNetmask(markEdit.getIpText());
                    }
                }else{
                    showRightBtn(true);
                }
            }
        }
    }


    @Override
    protected void onSetupFailed() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_network_settings);
        hideActionBar();
        mDeviceSettingsInfo = getIntent().getParcelableExtra(DeviceSettingsActivity.EXT_DEVICE_INFO);
        mCamera = mDeviceSettingsInfo == null? null : CameraHub.getInstance().getCamera(mDeviceSettingsInfo.uuid);
        if (mCamera != null) {
            mCamera.registerICameraListenerAndConnect(this);
        }
        mSMsgAVIoctrlIPCONFIGResp = getIntent().getParcelableExtra(NETWORK_CONFIG);
        initView();
        initData();
    }


    private void initIPConfigView(){
        ipAdress = findViewById(R.id.settings_ip);
        ndsEdit = findViewById(R.id.settings_nds);
        nds2Edit = findViewById(R.id.settings_spare_nds);
        markEdit = findViewById(R.id.settings_subnet_mask);
        gatewayEdit = findViewById(R.id.settings_gateway);
        ipAdress.setIpEditTextWatcher(this);
        ndsEdit.setIpEditTextWatcher(this);
        nds2Edit.setIpEditTextWatcher(this);
        markEdit.setIpEditTextWatcher(this);
        gatewayEdit.setIpEditTextWatcher(this);
    }


    private void initData() {
        if (mSMsgAVIoctrlIPCONFIGResp != null){
            bDhcpEnabled = mSMsgAVIoctrlIPCONFIGResp.bDhcpEnabled;
            autoSettingItem.setCheck(bDhcpEnabled == 1);
            manuSettingItem.setCheck(bDhcpEnabled != 1);
        }else{
            autoSettingItem.setCheck(true);
            manuSettingItem.setCheck(false);
        }
        ipAdress.setFocusValid(false);
        ndsEdit.setFocusValid(false);
        nds2Edit.setFocusValid(false);
        markEdit.setFocusValid(false);
        gatewayEdit.setFocusValid(false);
        if (bDhcpEnabled == 1) {
            findViewById(R.id.settings_network_info).setVisibility(View.GONE);
        } else {
            findViewById(R.id.settings_network_info).setVisibility(View.VISIBLE);
        }

        setNetworkConfig();
        TGThreadPool.executeOnUiThreadDelayed(() -> {
            ipAdress.setFocusValid(true);
            ndsEdit.setFocusValid(true);
            nds2Edit.setFocusValid(true);
            markEdit.setFocusValid(true);
            gatewayEdit.setFocusValid(true);
        }, 100);
    }

    private void setNetworkConfig() {
        if (mSMsgAVIoctrlIPCONFIGResp != null){
            ipAdress.setIpText(new String(mSMsgAVIoctrlIPCONFIGResp.ip));
            markEdit.setIpText(new String(mSMsgAVIoctrlIPCONFIGResp.netmask));
            ndsEdit.setIpText(new String(mSMsgAVIoctrlIPCONFIGResp.dns1));
            nds2Edit.setIpText(new String(mSMsgAVIoctrlIPCONFIGResp.dns2));
            gatewayEdit.setIpText(new String(mSMsgAVIoctrlIPCONFIGResp.gateway));
        }
    }

    @Override
    protected void initView() {
        setLeftBtn();
        modifyToolBar(R.string.txt_network_setting);
        setRightBtn();
        initListView();
        initIPConfigView();
    }

    private void goBack() {
        mHandler.removeCallbacks(timeRunable);
        Intent resultIntent = new Intent();
        resultIntent.putExtra(NETWORK_CONFIG, mSMsgAVIoctrlIPCONFIGResp);
        //设置返回数据
        setResult(RESULT_OK, resultIntent);//设置给之前启动它的activity的一个返回码
        this.finish();
    }

    private void setLeftBtn() {
        setClickBack(v -> {
            List<String> list = getIPConfigFromView();
            if (!mSaved || !TGDevice.getInstance().isNetwork(mCamera) || (list.size() == 0 && AUTO_CONFIG_VAL != bDhcpEnabled)){
                goBack();
            }else{
                DialogUtil.openDlalog(NetworkSettingsActivity.this, getString(R.string.txt_config_save),
                        null,
                        getString(R.string.saved),
                        getString(R.string.txt_cannel_save), v12 -> {
                            save();
                            goBack();
                        }, v1 -> goBack(), ResourcesUtil.getResources().getColor(R.color.drive_btn_record_selected));
            }
        });
    }

    private void showView(boolean autoSettingClick){
        autoSettingItem.setCheck(autoSettingClick);
        manuSettingItem.setCheck(!autoSettingClick);
        bDhcpEnabled = autoSettingClick ? AUTO_CONFIG_VAL : 0;
        findViewById(R.id.settings_network_info).setVisibility(autoSettingClick? View.GONE : View.VISIBLE);
        showRightBtn(true);
    }

    private void initListView() {
        autoSettingItem = findViewById(R.id.tv_auto_config);
        manuSettingItem = findViewById(R.id.tv_manu_config);
        autoSettingItem.setOnClickListener(v -> {
            if (!autoSettingItem.isCheck()){
                showView(true);
            }

        });
        manuSettingItem.setOnClickListener(v -> {
            if (!manuSettingItem.isCheck()){
                showView(false);
            }
        });
    }

    private void setRightBtn() {
        TextView right = findViewById(R.id.text_toolbar_right2);
        right.setText(R.string.saved);
        right.setTextColor(Color.parseColor("#3BBEFF"));
        right.setOnClickListener(v -> save());
    }

    private void showRightBtn(boolean show){
        mSaved = show;
        TextView right = findViewById(R.id.text_toolbar_right2);
        right.setVisibility(show? View.VISIBLE : View.GONE);
    }

    private List<String> getIPConfigFromView(){
        List<String> list = new ArrayList<>();
        String ip, mark, gateway, nds, nds2;
        if (AUTO_CONFIG_VAL == bDhcpEnabled && mSMsgAVIoctrlIPCONFIGResp != null){
            ip = new String(mSMsgAVIoctrlIPCONFIGResp.ip);
            mark = new String(mSMsgAVIoctrlIPCONFIGResp.netmask);
            gateway = new String(mSMsgAVIoctrlIPCONFIGResp.gateway);
            nds = new String(mSMsgAVIoctrlIPCONFIGResp.dns1);
            nds2 = new String(mSMsgAVIoctrlIPCONFIGResp.dns2);
        }else{
            ip = ipAdress.getIpText();
            mark = markEdit.getIpText();
            gateway = gatewayEdit.getIpText();
            nds = ndsEdit.getIpText();
            nds2 = nds2Edit.getIpText();
        }

        if (StringUtils.isEmpty(ip) || StringUtils.isEmpty(mark) || StringUtils.isEmpty(gateway) || StringUtils.isEmpty(nds) || StringUtils.isEmpty(nds2)){
            return list;
        }
        list.add(ip);
        list.add(mark);
        list.add(gateway);
        list.add(nds);
        list.add(nds2);

        return list;
    }

    private void save() {
        if (!TGDevice.getInstance().isNetwork(mCamera)){
            TGToast.showToast(R.string.txt_network_anomaly);
            return;
        }
        List<String> list = getIPConfigFromView();
        if (bDhcpEnabled != AUTO_CONFIG_VAL && list.size() == 0){
            TGToast.showToast(R.string.txt_ip_invalid_save_failed);
            return;
        }
        showRightBtn(false);
        if (mSMsgAVIoctrlIPCONFIGResp != null){
            mCamera.sendIOCtrl(AVIOCTRLDEFs.TCI_CMD_SET_IPCONFIG_REQ, mSMsgAVIoctrlIPCONFIGResp.parseContent(bDhcpEnabled, list.get(0), list.get(1), list.get(2), list.get(3), list.get(4)));
        }else{
            mCamera.sendIOCtrl(AVIOCTRLDEFs.TCI_CMD_SET_IPCONFIG_REQ, SMsgAVIoctrlIPCONFIGRespBean.parseContentEx(bDhcpEnabled, list.get(0), list.get(1), list.get(2), list.get(3), list.get(4)));
        }

    }

    @Override
    public void change() {
        showRightBtn(true);
    }
}